<?php
require_once("XMLSports.php");
require_once("functions.php");

/*******************************************************
Function:	updateUScores($League)
Updated:	03/04/2008
Description:	calculates the user's straight score & weighted score.
				Intended to only be run once a week, on Tuesdays.
*******************************************************
*/
function updateUScores($League)
{				
	//Connect To Database
	//dbConnect();			
	//Get this week
	$CurrWeek = 8; //getWeek($League);

	//Get an Array of distinct users. 
	$SQL = "SELECT DISTINCT UserID FROM ".$League."Picks ORDER BY UserID"; 
	$IDresult = mysql_query($SQL) or die("Cannot query the database.<br/>");
	 //loop through each user, checking to see which games they picked correctly.
	 do{
		if ($IDrow["UserID"] != "")
		{
		//declare a variable score to hold number of correct picks, set to zero
		$Score = 0;
		$WeightedScore = 0;
		//loop through weeks
		if ($CurrWeek > 17)	#Then it's playoff time//reset scores based on playoff games
			$startweek = 18;
		else
			$startweek = 1;
		for ($i = $startweek; $i < $CurrWeek; $i++)
		{
			/*Get number of games for this week; Most weeks have 16 games, 
			  8 weeks have only 14 games (4 teams have Byes)  */
			$SQL = "SELECT COUNT(*) AS GameCount FROM ".$League."Schedule Where Week=".$i;
			$result = mysql_query($SQL) or die("Cannot query the database.<br/>");
			if($myrow = mysql_fetch_array($result))
				$GameCount = $myrow["GameCount"];
		
			//loop through games for the week
			for ($j = 1; $j <= $GameCount; $j++)
			{
				//Get winner data from Schedule for week $i
				$SQL = "SELECT Winner FROM ".$League."Schedule Where ((GameNum=".$j.") AND (Week=".$i."))";
				$WinnerResult = mysql_query($SQL) or die("Cannot query the database.<br/>");
				if($Winnerrow = mysql_fetch_array($WinnerResult))
				{
					// Look for weighted picks
					/*
					$SQL = "SELECT Game".$j."Rank FROM ".$League."WeighPicks Where (UserID=".$IDrow["UserID"]." AND Week=".$i.")";
					$WeighPicksresult = mysql_query($SQL) or die("Cannot query the database.<br/>");
					if($WeighPicksrow = mysql_fetch_array($WeighPicksresult))
						$Rank = $WeighPicksrow["Game".$j."Rank"];
					else
						$Rank = 0;
						*/
					
					//Write SQL Query to extract specified data
					$SQL = "SELECT Game".$j." FROM ".$League."Picks Where (UserID=".$IDrow["UserID"]." AND Week=".$i.")";
					//Open Record Set using SQL Query
					$Picksresult = mysql_query($SQL) or die("Cannot query the database.<br/>");
					if($Picksrow = mysql_fetch_array($Picksresult))
					{
						if (($Picksrow["Game".$j] == $Winnerrow["Winner"]) && ($Winnerrow["Winner"] != ""))
						{
							$Score++;
							/*
							if ($Rank)
								$WeightedScore += $Rank;//$Picksrow["Game".$j."Rank"];
							else
								$WeightedScore++;
							*/
						}//end if ($Picksrow["Game".$j] == $Winnerrow["Winner"])
					}//end if($Picksrow...
				}//end if($Winnerrow = mysql_fetch_array($WinnerResult))
			}//end FOR LOOP looping through games for that week
		 }//end FOR LOOP looping through weeks
		
		 //echo "User #".$IDrow["UserID"]." has a score of ".$Score.".<BR>";		
		 //Update the user's score
		 //mysql_query("UPDATE ".$League."Users SET Score = ".$Score.", WeightedScore = ".$WeightedScore." WHERE ID=".$IDrow["UserID"]) or die("Cannot query the database.<br/>");
		 mysql_query("UPDATE ".$League."Users SET Score = ".$Score." WHERE ID=".$IDrow["UserID"]) or die("Cannot query the database.<br/>");
		}//end if ($IDrow["UserID"] != "")
	 }while($IDrow = mysql_fetch_array($IDresult));
}

/*******************************************************
Function:	resetTeamInfo()
Updated:	03/04/2008
Description:	Resets all of the team win/loss/ points information back to zero.
				Then walks through each week up until currentweek, recalculating
				based on the scrape.php script which scrapes ESPN website for scores.
********************************************************/				
function resetTeamInfo($League)
{				
	//Connect To Database
	dbConnect();			
	//Get this week
	$CurrWeek = getWeek($League);
			 
	// Reset all the team win/loss information.
	echo "Resetting team info...<br/>";
	$SQL = "UPDATE ".$League."Teams SET Wins=0,Loses=0,Ties=0,PointsFor=0,PointsAgainst=0,HomeWins=0,HomeLosses=0,RoadWins=0,RoadLosses=0,AFCWins=0,AFCLosses=0,NFCWins=0,NFCLosses=0,DivWins=0,DivLosses=0,Streak='W 0'";
	mysql_query($SQL) or die("Cannot query the database.<br/>");

	// Reset all the winners in ".$League."Schedule.
	echo "Resetting winners...<br/><br/>";
	$SQL = "UPDATE ".$League."Schedule SET Winner='-'";
	mysql_query($SQL) or die("Cannot query the database.<br/>");
	 
	// Loop through each week and reScrape
	for ($i = 1; $i <= $CurrWeek; $i++)
	{
		echo "Begining week <b>$i</b><br/>";
		$filename = "../".$League."/rss/".getSeasonYear($League)."/week".$i.".xml";
		//Create New XMLSports Generator
		$myXMLSports = new XMLSports;
		//SET THE WEEK
		$myXMLSports->SetWeek($i);
		//Set Output File Name
		$myXMLSports->setOutputFile($filename);
		//Generate The New SportsML XML file
		$myXMLSports->generate();
		echo "<B>Done with week $i</B><br/><br/>";
	}
	echo "<br/>Done resetting team info!<br/>";
}

/*******************************************************
Function:	updateURanks()
Updated:	03/04/2008
Description:	Updates the user's ranks base don straight score.
				Intended to only be run once a week, on Tuesdays
				AFTER the userScores have been updated.
********************************************************/
function updateURanks($League)
{				
	//Connect To Database
	//dbConnect();			
	//Get this week
	$//CurrWeek = getWeek($League);
	//Get an Array of distinct teams.
	$SQL = "SELECT ID, Score, Rank FROM ".$League."Users ORDER BY Score DESC";
	$result = mysql_query($SQL) or die("Cannot query the database.<br/>");
	$Rank = 1;
	$PrevScore = 0;
	do{//loop through each user and set thier rank & prev rank
		if ($myrow["ID"] != "")
		{
			if ($PrevScore == $myrow["Score"])
			{
				//users are tied
			} else
			{
				$SetRank = $Rank;
			}
			$PrevScore = $myrow["Score"];
			$Rank++;
			$SQL = "UPDATE ".$League."Users SET Rank = ".$SetRank.", PrevRank = ".$myrow["Rank"]." WHERE ID = ".$myrow["ID"];
			mysql_query($SQL) or die("Cannot query the database.<br/>");
		}//end if ($IDrow["UserID"] != "")
	}while($myrow = mysql_fetch_array($result));	
	updatePicksMade($League);			
}

/*******************************************************
Function:	updatePicksMade()
Updated:	03/04/2008
Description:	Counts the number of pick the user has made from week 1 to
				the current week.
********************************************************/
function updatePicksMade($League)
{				
	//Connect To Database
	//dbConnect();
	//Get this week
	$CurrWeek = 8; //getWeek($League);
	
	//Write SQL Query to extract specified data
	$SQL = "SELECT ID FROM ".$League."Users";
	
	//Open Record Set using SQL Query
	$result = mysql_query($SQL) or die("Cannot query the database.<br/>");
	
	do{
		if (($myrow["ID"] != Null) || ($myrow["ID"] != "")) {
			$PicksMade = 0;
			//Write SQL Query to extract specified data
			$SQL = "SELECT * FROM ".$League."Picks Where ((UserID=".$myrow["ID"].") AND (Week<=".$CurrWeek."))";
			//Open Record Set using SQL Query
			
			$Picksresult = mysql_query($SQL) or die("Cannot query the database.<br/>");
			do {
				for ($j = 1; $j <= 16; $j++)
				{
					if (($pickrow["Game".$j] != Null) || ($pickrow["Game".$j] != "")) 
					{
						$jSQL = "SELECT Winner FROM ".$League."Schedule WHERE ((GameNum = $j) AND (Week=".$pickrow["Week"]."))";
						$jresult = mysql_query($jSQL) or die("Cannot query the database.<br/>");
						$jrow =  mysql_fetch_array($jresult);
						if($jrow["Winner"] != "-")
							$PicksMade++;//do nothing, this game has been scored so pick counts
						//else   Game not scored yet.
					}//end if
				}//end FOR Loop
			}while($pickrow = mysql_fetch_array($Picksresult));
			$updateSQL = "UPDATE ".$League."Users SET PicksMade=$PicksMade WHERE ID=".$myrow["ID"];
			//Open Record Set using SQL Query
			$updateresult = mysql_query($updateSQL) or die("Cannot query the database.<br/>");
		}
	}while($myrow = mysql_fetch_array($result));					

}

/*******************************************************
Function:	updateSurvivors($Week, $League)
Updated:	03/04/2008
Description:	Checks to see if the user's Survivor Pick was correct and
				eliminate the user if incorrect.
********************************************************/
function updateSurvivors($Week, $League)
{
	// Get all teams from ".$League."Schedule table for week = $Week
	$SQL = "SELECT UserID, Pick FROM ".$League."SurvivalPicks WHERE Week=$Week";
	$result = mysql_query($SQL) or die("Cannot query the database.<br/>");
	while($myrow = mysql_fetch_array($result))	//Loop through list of games, add both Home & Away teams to list
	{
		$InsideSQL = "SELECT Winner FROM ".$League."Schedule WHERE Winner='".$myrow["Pick"]."' AND Week=$Week";
		mysql_query($InsideSQL);
		if(mysql_affected_rows() > 0)
			echo "user # ".$myrow["UserID"]." has survived for week $Week<br/>";
		else
			mysql_query("UPDATE ".$League."Users SET Survivor='OUT' WHERE ID=".$myrow["UserID"]);
	}
}

/*******************************************************
Function:	updateUserSeriesScores($League)
Updated:	04/17/2008
Description:	calculates the user's series score.
*******************************************************
*/
function updateUserSeriesScores($League)
{				
	$query="SELECT * FROM ".$League."Series Where Team1 <> 'TBD' ORDER BY Week";
	$doQuery=mysql_query($query);
	$numrows=mysql_num_rows($doQuery);
	$num = 1;
	if($numrows > 0)
	{
		while($results=mysql_fetch_array($doQuery))
		{
			//Fill Arrays With Data
			$homeTeams[$num]=$results['Team2'];
			$awayTeams[$num]=$results['Team1'];
			$winners[$num]=$results['Winner'];
			$GameNums[$num]=$results['NumGames'];
			$num++;
		}
			
		//Get Data From Users Who Picked
		$UserPickedSQL = "SELECT DISTINCT UserID FROM ".$League."SeriesPicks WHERE Team IS NOT NULL ORDER BY UserID ASC";
		$UserPickedresult = mysql_query($UserPickedSQL) or die("Cannot query the database for if user picked.<br>");
		$row = 0;
		do{
			if ($myrow["UserID"] != NULL)
			{						
				$SeriesScore = 0;
				$GameNumPickScore = 0;
				for($j = 1; $j <= $numrows; $j++)
				{	
					$insideSQL = "SELECT Team FROM ".$League."SeriesPicks WHERE UserID = ".$myrow["UserID"]." AND Week = $j AND Team IS NOT NULL ORDER BY UserID ASC";
					$insidePickedresult = mysql_query($insideSQL) or die("Cannot query the database for user picks.<br>");
					
					$insiderow = mysql_fetch_array($insidePickedresult);
					$pick = $insiderow["Team"];
	
					if($winners[$j] != "-")
					{
						if($pick == $winners[$j])
						{
							switch(true)
							{
								case ($j < 9):
									$SeriesScore+=5;
									break;
								case (($j >= 9) && ($j < 13)):
									$SeriesScore+=8;
									break;
								case (($j >= 13) && ($j < 15)):
									$SeriesScore+=12;
									break;
								case ($j == 15):
									$SeriesScore+=15;
									break;
							}
						}
					}
					
				}
				
				//Show user's pick for Number of game the best-of-seven series will last..
				for($j = 1; $j <= $numrows; $j++)
				{	
					$insideSQL = "SELECT NumGames FROM ".$League."SeriesPicks WHERE UserID = ".$myrow["UserID"]." AND Week = $j AND Team IS NOT NULL ORDER BY UserID ASC";
					$insidePickedresult = mysql_query($insideSQL) or die("Cannot query the database for user picks.<br/>");
					
					$insiderow = mysql_fetch_array($insidePickedresult);
					$pick = $insiderow["NumGames"];
	
					if($GameNums[$j] != 0)
					{
						if($pick == $GameNums[$j])
						{
							switch(true)
							{
								case ($j < 13):
									$GameNumPickScore+=2;
									break;
								case (($j >= 13) && ($j < 15)):
									$GameNumPickScore+=3;
									break;
								case ($j == 15):
									$GameNumPickScore+=5;
									break;
							}
						}
					}
					
				}
				//Update the Users SeriesSCore
				$SQL = "UPDATE ".$League."Users SET SeriesScore=".($SeriesScore + $GameNumPickScore)." WHERE UserID = ".$myrow["UserID"];
				mysql_query($SQL) or die("Cannot query the database to update user series score.<br/>");
				$row++;
			}
		}while($myrow = mysql_fetch_array($UserPickedresult));
	}
}